/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package protocol;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import server.managerServer.executors.ExecutorCreatePoll;

/**
 *
 * @author radu
 */

public class MessageUpdate extends Message {

    int[] optionCount;
    long pollId;

    public MessageUpdate(Element root) {

        pollId = Integer.valueOf(root.getAttribute("id"));
        NodeList options = root.getElementsByTagName("option");
        //TODO : more testing on correcteness of the message
        //TODO: ensure that the length of options is > 0
        optionCount = new int[options.getLength()];
        for (int i = 0; i < options.getLength(); i++) {
            
            Node option = options.item(i);

            if (option.getNodeType() == Node.ELEMENT_NODE) {
                Element optionElem = (Element) option;

                //TODO : test that ord is not bigger than the number of options

                //TODO : ensure that the same ord is not given twice
                int ord = Integer.valueOf(optionElem.getAttribute("ord"));
                optionCount[ord] = Integer.valueOf(optionElem.getTextContent());
            }
        }
    }

    public MessageUpdate(int[] optionCnt, long _pollId) {
        optionCount = optionCnt;
        this.pollId = _pollId;
    }

    @Override
    public String toString() {
        String str = "<update id=\""+pollId+"\">";

        for (int i = 0; i < optionCount.length; i++) {
            str += "<option ord=\"" + i + "\">" + optionCount[i] + "</option>";
        }
        str += "</update>\r\n";

        return str;
    }

    @Override
    public Executor getServerExecutor() {
        return new ExecutorCreatePoll(this);
    }

    public int[] getOptionCount() {
        return optionCount;
    }

    public long getPollId() {
        return pollId;
    }
    
    

    
}
